package user

import (
	"gpt-api/framework/codes"
	"gpt-api/framework/ginplus"
	"gpt-api/pkg/model"
	"gpt-api/pkg/response"
	"gpt-api/pkg/util"

	"github.com/gin-gonic/gin"
)

// 获取用户邀请码
func (h *Handler) GetInviteCode(c *gin.Context) error {
	userId := ginplus.GetUserID(c)

	// 查询用户信息
	user, err := (&model.Users{}).GetUserInfoById(h.db, userId)
	if err != nil {
		return ginplus.ReplyError(c, codes.UserNotFound, err)
	}

	// 如果用户没有邀请码，则生成一个
	if user.InviteCode == "" {
		inviteCode, err := util.GenerateNonce(20)
		if err != nil {
			return ginplus.ReplyBadRequest(c, err)
		}
		user.InviteCode = inviteCode
		err = user.Update(h.db)
		if err != nil {
			return ginplus.ReplyError(c, codes.UserNotFound, err)
		}
	}

	// 返回邀请码
	inviteCodeResp := response.InviteCodeResp{InviteCode: user.InviteCode}
	return ginplus.ReplyJSON(c, inviteCodeResp)
}

// 获取用户邀请记录
func (h *Handler) GetInviteRecord(c *gin.Context) error {
	// 验证参数
	var req struct {
		Page int `form:"page" default:"1"`
		Size int `form:"size" default:"10"`
		Type int `form:"type" default:"1"`
	}
	if err := c.Bind(&req); err != nil {
		return ginplus.ReplyBadRequest(c, err)
	}

	var resp []response.InviteRecordResp

	// 查询用户邀请现金记录
	if req.Type == 1 {
		records, err := (&model.Business{}).GetBusinessRecordByUserIdByInvite(h.db, ginplus.GetUserID(c), req.Page, req.Size)
		if err != nil {
			return ginplus.ReplyBadRequest(c, err)
		}

		// 整理列表
		for _, record := range records {
			resp = append(resp, response.InviteRecordResp{
				Username:     record.InviteUser.Username,
				Avatar:       record.InviteUser.Avatar,
				RewardAmount: float32(record.Amount),
			})
		}
	}

	// 查询用户邀请积分记录
	if req.Type == 2 {
		scoreRecords, err := (&model.Score{}).GetInviteScoreByUserId(h.db, ginplus.GetUserID(c), req.Page, req.Size)
		if err != nil {
			return ginplus.ReplyBadRequest(c, err)
		}

		// 整理列表
		for _, record := range scoreRecords {
			// 如果邀请人头像和用户名为空,默认赋值
			if record.InviteUser.Avatar == "" {
				record.InviteUser.Avatar = "https://yq-1301100205.cos.ap-beijing.myqcloud.com/yq/picture/2024/11/991825d20344e3275e674c2f9e86a268.png"
			}
			if record.InviteUser.Username == "" {
				record.InviteUser.Username = "新用户"
			}
			resp = append(resp, response.InviteRecordResp{
				Username:    record.InviteUser.Username,
				Avatar:      record.InviteUser.Avatar,
				RewardScore: record.Score,
			})
		}
	}

	// 	查询统计邀请人数和金额
	count, inviteAmount, inviteScore, err := (&model.Business{}).GetInviteCountAmountByUserId(h.db, ginplus.GetUserID(c))
	if err != nil {
		return ginplus.ReplyBadRequest(c, err)
	}

	return ginplus.ReplyJSON(c, gin.H{"page": req.Page, "list": resp, "invite_count": count, "invite_amount": inviteAmount, "invite_score": inviteScore})
}
